import * as resize from "./system/resize"
import * as THREE from "three"
import Stats from 'three/addons/libs/stats.module.js';
import { createCamera } from "./base/camera"
import { createScene } from "./base/scene"
import { createRenderer } from "./base/renderer"
import addLight from "./base/light"
import { gameUpdate, gameInit } from "./main/game"
import { gui } from "./system/gui";
const stats = new Stats();
stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
// stats.dom.style.top = "20%"
const obj = {
    showStats: false
}
gui.add(obj, "showStats").name("是否显示帧率").onChange((value) => {
    if (value) {
        document.body.appendChild(stats.dom);
    }
    else {
        document.body.removeChild(stats.dom);
    }

})

class ThreeApp {
    container: HTMLElement;
    camera: THREE.PerspectiveCamera;
    scene: THREE.Scene;
    renderer: THREE.WebGLRenderer;
    tick: () => void;
    mixer: typeof THREE.AnimationMixer;
    control: any;
    constructor(container: HTMLElement) {
        this.container = container
        this.init()
        gameInit(this)
    }
    init() {
        // 相机 camera
        this.camera = createCamera()
        // 场景 scene
        this.scene = createScene()
        // 光源
        addLight(this.scene)
        // 渲染器 renderer
        this.renderer = createRenderer(this.container)
        // resize
        resize.resizeEventListener(this.camera, this.renderer)
    }
    game() {

    }
    render() {
        // 渲染场景
        const clock = new THREE.Clock()
        let previousTime = 0
        const STEPS_PER_FRAME = 5;
        this.tick = () => {
            stats.update()
            const deltaTime = Math.min(0.05, clock.getDelta()) / STEPS_PER_FRAME
            const elapsedTime = clock.getElapsedTime()
            const mixerUpdateDelta = elapsedTime - previousTime
            previousTime = elapsedTime

            for (let i = 0; i < STEPS_PER_FRAME; i++) {
                gameUpdate(deltaTime)
            }
            if (this.mixer instanceof THREE.AnimationMixer) {
                this.mixer.update(mixerUpdateDelta)
            }
            this.renderer.render(this.scene, this.camera)
            window.requestAnimationFrame(this.tick)
        }
        this.tick()
    }
    clear() {
        location.reload()
        resize.clear()
        // @ts-ignore
        this.tick = null
        // @ts-ignore
        this.scene = null
        // @ts-ignore
        this.camera = null
        this.renderer.dispose()
        this.control.dispose()
    }
}

export { ThreeApp }